﻿using Autofac;
using Autofac.Core;
using Autofac.Integration.Mvc;
using Nop.Core.Data;
using Nop.Core.Infrastructure;
using Nop.Core.Infrastructure.DependencyManagement;
using Nop.Data;
using Spotshub.Plugin.Payments.GlobalPayments.Services;

namespace Spotshub.Plugin.Payments.GlobalPayments
{
    public class DependencyRegistrar : IDependencyRegistrar
    {
        public virtual void Register(ContainerBuilder builder, ITypeFinder typeFinder)
        {
            const string serviceName = "nop_object_context_payments_global_payments";
            //Register services
            builder.RegisterType<GlobalPaymentsService>().As<IGlobalPaymentsService>();

            ////data layer
            var dataSettingsManager = new DataSettingsManager();
            var dataProviderSettings = dataSettingsManager.LoadSettings();

            if (dataProviderSettings != null && dataProviderSettings.IsValid())
            {
                //register named context
                builder.Register<IDbContext>(c => new GlobalPaymentsObjectContext(dataProviderSettings.DataConnectionString))
                    .Named<IDbContext>(serviceName)
                    .InstancePerLifetimeScope();

                builder.Register<GlobalPaymentsObjectContext>(c => new GlobalPaymentsObjectContext(dataProviderSettings.DataConnectionString))
                    .InstancePerLifetimeScope();
            }
            else
            {
                //Register entity context
                builder.Register<IDbContext>(c => new GlobalPaymentsObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .Named<IDbContext>(serviceName)
                    .InstancePerLifetimeScope();
                builder.Register<GlobalPaymentsObjectContext>(c => new GlobalPaymentsObjectContext(c.Resolve<DataSettings>().DataConnectionString))
                    .InstancePerLifetimeScope();
            }

            //override required repository with our custom context
            builder.RegisterType<EfRepository<PaymentCreditCard>>()
                .As<IRepository<PaymentCreditCard>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(serviceName))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<PaymentProfile>>()
                .As<IRepository<PaymentProfile>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(serviceName))
                .InstancePerLifetimeScope();

            builder.RegisterType<EfRepository<PaymentTransaction>>()
                .As<IRepository<PaymentTransaction>>()
                .WithParameter(ResolvedParameter.ForNamed<IDbContext>(serviceName))
                .InstancePerLifetimeScope();
        }

        public int Order
        {
            get { return 1; }
        }
    }
}
